const http = require('../../utils/http.js');
const app = getApp();
const { $Toast } = require('../../dist/base/index');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    startX: 0, //开始坐标
    startY: 0,
    delBtnWidth: 65,
    list: [],
    totalPrice: 0, //总价
    allSelect: false, //默认不全选
    showOrder: false,

    isclick: false,
    remarks:'',
  },

  //获取本地购物车列表
  getShopList() {
    var shopCar = wx.getStorageSync('shopCar') || [];
    console.log(shopCar)
    if (shopCar.length>0){
      var qisong = shopCar[shopCar.length-1].start_fee;
      this.setData({
        qisong
      });
    }
    this.setData({
      list: shopCar
    });
    // if (shopCar.every((item1, index1) => {
    //   return item1.is_select;
    // })) {
    //   this.setData({
    //     allSelect: true
    //   })
    // } else {
    //   this.setData({
    //     allSelect: false
    //   })
    // }
   
  },

  //计算总价
  getTotal() {
    var shopCar = this.data.list;
    var totalPrice = 0;
    if (this.data.showOrder){
      var platformFeer = this.data.platformFeer / 1;
      
    }else{
      var platformFeer = 0
    }
    
    var shopCar1 = shopCar.filter((item, index) => {
      return item.is_select
    })
    shopCar1.forEach((item, index) => {
      totalPrice += (item.goods_nowprice * item.goods_sl);
    })

    if (totalPrice>=this.data.free_fee  ){
      var platformFeer = 0;
      this.setData({
        platformFeer
      })
    }
    
    console.log(this.data.free_fee,totalPrice,platformFeer)
    this.setData({
      totalPrice: totalPrice + platformFeer, //总价
      goodsPrice: totalPrice //商品价格
    })
    
   

  },

  //商品全选
  allSelect() {

    this.setData({
      allSelect: !this.data.allSelect
    })
    var shopCar = wx.getStorageSync('shopCar') || [];

    if (this.data.allSelect == true) {
      shopCar.forEach((item, index) => {
        item.is_select = true
      })
      this.setData({
        list: shopCar
      })
    } else {
      shopCar.forEach((item, index) => {
        item.is_select = false
        this.setData({
          list: shopCar
        })
      })
    }

    this.getTotal();
  },

  //商品单选
  radioSelect(e) {
    var gid = e.currentTarget.dataset.id;
    console.log(gid)
    var shopCar = this.data.list;
    shopCar.some((item, index) => {
      if (gid == item.gid) {
        item.is_select = !item.is_select;
        return true;
      }
    })

    if (shopCar.every((item1, index1) => {
      return item1.is_select;
    })) {
      this.setData({
        allSelect: true
      })
    } else {
      this.setData({
        allSelect: false
      })
    }

    this.setData({
      list: shopCar
    })
    this.getTotal();
  },

  //商品数量加
  addNum(e) {
    var gid = e.currentTarget.dataset.id;
    var shopCar = this.data.list;
    shopCar.forEach((item, index) => {
      if (item.gid == gid) {
        item.goods_sl++
      }
    })
    this.setData({
      list: shopCar
    })

    wx.setStorageSync('shopCar', shopCar);
    this.getTotal();
  },

  //商品数量减
  reduceNum(e) {
    var gid = e.currentTarget.dataset.id;
    var shopCar = this.data.list;
    shopCar.forEach((item, index) => {
      if (item.gid == gid) {
        item.goods_sl--
        if (item.goods_sl < 1) { item.goods_sl = 1 }
      }
    })
    this.setData({
      list: shopCar
    })
    wx.setStorageSync('shopCar', shopCar);
    this.getTotal();
  },

  //删除
  delItem(e) {
    var gid = e.currentTarget.dataset.id;
    var shopCar = this.data.list;

    shopCar.forEach((item, index) => {
      if (item.gid == gid) {
        shopCar.splice(index, 1);
      }
    })
    this.setData({
      list: shopCar
    })
    this.getTotal();
    //更新缓存数据
    wx.setStorageSync('shopCar', shopCar);

  },

  //清空购物车
  emptyItem() {
   
    wx.showModal({
      title: '提示',
      content: '确定清空购物车?',
      success:(res) =>{
        if (res.confirm) {
          this.setData({
            list: []
          })
          //更新缓存数据
          wx.removeStorageSync('shopCar')
        } else if (res.cancel) {
          
        }
      }
    })
  },

  touchS: function (e) {

    if (e.touches.length == 1) {
      this.setData({
        //设置触摸起始点水平方向位置
        startX: e.touches[0].clientX
      });
    }
  },

  touchM: function (e) {
    if (e.touches.length == 1) {
      //手指移动时水平方向位置
      var moveX = e.touches[0].clientX;
      //手指起始点位置与移动期间的差值
      var disX = this.data.startX - moveX;
      var delBtnWidth = this.data.delBtnWidth;
      var txtStyle = "";
      if (disX == 0 || disX < 0) { //如果移动距离小于等于0，说明向右滑动，文本层位置不变
        txtStyle = "left:0px;";
      } else if (disX > 0) { //移动距离大于0，文本层left值等于手指移动距离
        txtStyle = "left:-" + disX + "px";
        if (disX >= delBtnWidth) {
          //控制手指移动距离最大值为删除按钮的宽度
          txtStyle = "left:-" + delBtnWidth + "px";
        }
      }
      //获取手指触摸的是哪一项
      var index = e.currentTarget.dataset.index;
      var list = this.data.list;
      list[index].txtStyle = txtStyle;
      //更新列表的状态
      this.setData({
        list: list
      });
    }
  },
  touchE: function (e) {
    if (e.changedTouches.length == 1) {
      //手指移动结束后水平位置
      var endX = e.changedTouches[0].clientX;
      //触摸开始与结束，手指移动的距离
      var disX = this.data.startX - endX;
      var delBtnWidth = this.data.delBtnWidth;
      //如果距离小于删除按钮的1/2，不显示删除按钮
      var txtStyle = disX > delBtnWidth / 2 ? "left:-" + delBtnWidth + "px" : "left:0px";
      //获取手指触摸的是哪一项
      var index = e.currentTarget.dataset.index;
      var list = this.data.list;
      list[index].txtStyle = txtStyle;
      //更新列表的状态
      this.setData({
        list: list
      });
    }
  },

  //选择收货地址
  chooseAddress() {
    wx.navigateTo({
      url: '../goodsAddress/goodsAddress?page=takeExpress',
    })
  },

  //填写备注
  fillInNotice(e){
    console.log(e.detail.value);
    var remarks = e.detail.value
    this.setData({
      remarks
    })
  },

  //提交订单
  subOrder() {

   
    var shopCar = this.data.list;
    if (shopCar.every((item, index) => {
      return !item.is_select
    })) {
     // http.showToast('请选择商品!' + '', '', 'none');
      $Toast({
        content: '请选择商品!'
      });
      return
    }
    console.log(this.data.qisong)
    if (this.data.totalPrice < this.data.qisong) {
    //  http.showToast(`商品必须满${this.data.qisong}元起送` + '', '', 'none');
      $Toast({
        content: `商品必须满${this.data.qisong}元起送`
      });
      return
    }
    var goods1 = shopCar.filter(item => item.is_select);
    this.setData({
      goods1,
      showOrder: true
    })
   
    this.getTotal();

    
  },

  //立即支付
  payMoney() {

    if (!this.data.isclick){
      if (!wx.getStorageSync('nowAddress')){
        $Toast({
          content: '请选择地址!'
        });
        return
      }
      if (wx.getStorageSync('nowSchool').school_name !== wx.getStorageSync('nowAddress').school) {
        wx.showModal({
          title: '提示',
          content: '收货地址与学校不一致，请选择正确的学校',
          showCancel: false,
          confirmText: '我知道了'
        })

        return
      }

      var shopCar = this.data.list;
      var goods = [];
      var goods1 = shopCar.filter(item => item.is_select);
      goods1.forEach(item => {
        goods.push({
          id: item.gid,
          num: item.goods_sl
        })
      })


      var params = {
        uid: app.globalData.uid,
        goods: JSON.stringify(goods),
        school_id: wx.getStorageSync('nowSchool').id,
        jine: this.data.totalPrice,
        accesstoken: app.globalData.token,
        dizi: wx.getStorageSync('nowAddress').id,
        remarks:this.data.remarks
      }
      http.fetchApi('order_goods', params).then(res => {
        if (res.data.code == 1) {
          var orderId = res.data.results[0].orderid;
          var ddId = res.data.results[0].id;
          var total = res.data.results[0].zfje;

          wx.navigateTo({
            url: '../payment/payment?orderId=' + orderId + '&total=' + total + '&ddId=' + ddId,

          })
        } else if (res.data.code == 2){
          $Toast({
            content: '该店已打样!',
            type: 'warning'
          });

          return
        }
      })
    }else{
      
      $Toast({
        content: '不能重复提交!',
        type: 'warning'
      });
    }
   

    //防止多次点击
    this.setData({
      isclick: true
    })



  },

  //获取满减的金额
  getFullMoeny(){
  
      var shid = wx.getStorageSync('shopCar')[0].shid;
    
    
    http.fetchApi('procedure_t', { p: `R2015001|${shid}`}).then(res=>{
      if(res.data.code==1){
        var free_fee = res.data.results[0].free_fee;
      
        this.setData({
          free_fee
        })

        this.getTotal();
      }
    })


  },

  //获取商家跑腿费
  getShopPaotui(){
    var shid = wx.getStorageSync('shopCar')[0].shid;
    http.fetchApi('procedure_t', { p: `R2015002|${shid}` }).then(res=>{
      if(res.data.code==1){
        var platformFeer = res.data.results[0].peisong_fee;
        this.setData({
          platformFeer
        })
        this.getFullMoeny();
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // this.setData({
    //   platformFeer: app.globalData.platformFeer
    // })
    if (wx.getStorageSync('shopCar').length>0){
      this.getShopPaotui();
    }
    
    // this.getFullMoeny();
    this.getShopList();

    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //取出默认地址放到地址栏
    var uid = app.globalData.uid;
    http.fetchApi('procedure_t', { p: 'R2003008|' + uid }).then(res => {
      if (res.data.code == 1) {
        var addressArr = res.data.results;
        var defaultAddress = addressArr.filter(item => item.isdefault);

        if (!wx.getStorageSync('nowAddress')) {
          wx.setStorageSync('nowAddress', defaultAddress[0]);
          var nowAddress = wx.getStorageSync('nowAddress');

          this.setData({
            nowAddress
          })
        } else {
          var nowAddress = wx.getStorageSync('nowAddress');

          this.setData({
            nowAddress
          })
        }


      } else {
       // http.showToast('服务器好像出错啦!' + '', '', 'none')
        $Toast({
          content: '服务器好像出错啦!',
          type: 'error'
        });
      }
    })

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var shopCar = wx.getStorageSync('shopCar') || [];
    shopCar.forEach(item => {
      item.is_select = false
    })
    wx.setStorageSync('shopCar', shopCar)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})